package com.dly.blog.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dly.blog.annotation.IgnoreAccess;
import com.dly.blog.filter.JwtAuthenticationFilter;
import com.dly.blog.properties.BlogSecurityProperties;
import com.dly.blog.provider.AccountAuthenticationProvider;
import com.dly.blog.provider.EmailAuthenticationProvider;
import com.dly.blog.service.DefaultDetailsService;
import com.dly.blog.service.LogoutService;
import com.dly.blog.service.UserDetailsAuthService;
import com.dly.blog.utile.SpringContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/10 20:12
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity
@EnableConfigurationProperties(BlogSecurityProperties.class)
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    private final LogoutService logoutService;

    private final AuthenticationEntryPoint authenticationEntryPoint;

    private final AccessDeniedHandler accessDeniedHandler;

    private final BlogSecurityProperties blogSecurityProperties;


    private final RequestMappingHandlerMapping requestMappingHandlerMapping;

    /**
     * 放行静态的相关资源不走过滤器链
     * @return
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers(convertToArray(blogSecurityProperties.getStaticResources()));
    }

    /**
     * 获取所有需要放行的接口 通过过滤器放行
     * @return
     */
    private List<String> getIgnoreAccess(){
        Set<String> ignoreAccessUrl = new HashSet<>();
        //获取到所有的请求接口
        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();
        handlerMethodMap.forEach((k,v)->{
            if(ObjectUtil.isNotNull(getAnnotation(v, IgnoreAccess.class))){
                PathPatternsRequestCondition pathPatternsCondition = k.getPathPatternsCondition();
                if(ObjectUtil.isNotNull(pathPatternsCondition)){
                    ignoreAccessUrl.addAll(pathPatternsCondition.getPatterns().stream().map(PathPattern::getPatternString).toList());
                }
            }
        });
        return new ArrayList<>(ignoreAccessUrl);
    }

    public static <A> A getAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> annotationClass){
        A annotation = null;
        //获取方法
        Method method = handlerMethod.getMethod();
        //判断是否存在该注解
        if(method.isAnnotationPresent(annotationClass)){
            annotation = (A) method.getAnnotation(annotationClass);
        }else{
            //从声明类找
            Class<?> beanType = handlerMethod.getBeanType();
            if(beanType.isAnnotationPresent(annotationClass)){
                annotation = (A) beanType.getAnnotation(annotationClass);
            }
        }
        return annotation;
    }

    /**
     * 将 Set 转换为 String[]
     *
     * @param resources List
     * @return String[]
     */
    private String[] convertToArray(List<String> resources) {
        if (Objects.nonNull(resources) && !resources.isEmpty()) {
            String[] result = new String[resources.size()];
            return resources.toArray(result);
        } else {
            return new String[]{};
        }
    }

    /**
     * Security 跨域问题解决
     * @return
     */
    CorsConfigurationSource corsConfigurationSource() {
        // 提供CorsConfiguration实例，并配置跨域信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(List.of("*"));
        corsConfiguration.setAllowedMethods(List.of("*"));
        corsConfiguration.setAllowedOrigins(List.of("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http
    ) throws Exception {
        //关闭csrf
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(corsConfigurationSource()))
                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
                    //这些请求放行
                    authorizationManagerRequestMatcherRegistry.requestMatchers(convertToArray(getIgnoreAccess())).permitAll();
                    //这些请求进行拦截
                    authorizationManagerRequestMatcherRegistry.anyRequest().authenticated();
                })
                //失败处理
                .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
                    //认证失败处理
                    httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(authenticationEntryPoint);
                    //权限不足处理
                    httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler);
                })
                //使用无状态的session 基于token，所以不需要session
                .sessionManagement(httpSecuritySessionManagementConfigurer ->
                        httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //把jwt的过滤器 设置在用户触发登入之前
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                //退出登入处理
                .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer
                        .logoutUrl("/auth/logout")
                        .addLogoutHandler(logoutService)
                        .logoutSuccessHandler(((request, response, authentication) -> SecurityContextHolder.clearContext()))
                );
        return http.build();
    }

//    @Bean
//    public AuthenticationProvider authenticationProvider(UserDetailsAuthService userDetailsAuthService){
//        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
//        authProvider.setUserDetailsService(userDetailsAuthService);
//        authProvider.setPasswordEncoder(passwordEncoder());
//        return authProvider;
//    }

//    @Bean
//    public AccountAuthenticationProvider accountAuthenticationProvider(DefaultDetailsService defaultDetailsService){
//        AccountAuthenticationProvider accountAuthenticationProvider = new AccountAuthenticationProvider();
//        accountAuthenticationProvider.setDefaultDetailsService(defaultDetailsService);
//        accountAuthenticationProvider.setPasswordEncoder(passwordEncoder());
//        return accountAuthenticationProvider;
//    }
//
//    @Bean
//    public EmailAuthenticationProvider emailAuthenticationProvider(DefaultDetailsService defaultDetailsService){
//        EmailAuthenticationProvider emailAuthenticationProvider = new EmailAuthenticationProvider();
//        emailAuthenticationProvider.setDefaultDetailsService(defaultDetailsService);
//        emailAuthenticationProvider.setPasswordEncoder(passwordEncoder());
//        return emailAuthenticationProvider;
//    }

    /**
     * 密码加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 用于处理身份验证的核心接口。它负责验证用户的身份并生成相应的认证令牌。
     * @return
     * @throws Exception
     */
    @Bean
    public ProviderManager providerManager(List<AuthenticationProvider> lists, AuthenticationManager authenticationManager) throws Exception {
        return new ProviderManager(lists, authenticationManager);
    }

    /**
     * 注入全局认证的manager 自定义provider 无法使用自定义的provider
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
}
